<?php
/**
 * 微信公众号
 */
class WeiXinGongZhongHaoController extends WeixinClass
{

    public $appId='';
    public $appsecret='';

    /**
     *微信公众号接入
     */
    public function actionIndex(){
        define("TOKEN", "myWink");
        //$this->valid();exit;//微信服务器配置时,去掉注释
        $postStr = $GLOBALS["HTTP_RAW_POST_DATA"];
        //对post数据进行处理
        if (!empty($postStr)){

            $postObj = simplexml_load_string($postStr, 'SimpleXMLElement', LIBXML_NOCDATA);
            $fromUsername = $postObj->FromUserName;//用户加密微信号
            $toUsername = $postObj->ToUserName;
            $time = time();$date = date('Y-m-d',$time);
            $replyTitle=$this->replyBase($fromUsername,$toUsername,$time,$Content);
            $type=trim($postObj->MsgType);
            $keyword = trim($postObj->Content);
            //存储使用信息
            $filename="log/weixin.log";
            $handle=fopen($filename,"a+");
            $array=array('fromUsername'=>$fromUsername,'toUsername'=>$toUsername,'time'=>$time);
            $json=CJSON::encode($array);
            $str=fwrite($handle,$json."\r\n");

            fclose($handle);
            if($type == "event"){

                $filename="log/weixin_msg.log";
                $handle=fopen($filename,"a+");
                $array=array('fromUsername'=>$fromUsername,'toUsername'=>$toUsername,'event'=>$postObj->Event,'time'=>$time);
                $json=CJSON::encode($array);
                $str=fwrite($handle,$json."\r\n");

                //新关注
                if(trim($postObj->Event) == "subscribe"){
                    $replyBody=$this->replyText('/::*/::*');
                }elseif(trim($postObj->Event) == "unsubscribe"){

                }elseif(trim($postObj->Event) == "CLICK"){

                }
            }
            if($type=='text'){

                //绑定微信号
//				if(strstr($keyword,'##')){
//					if(strstr($keyword,'##01#')){
//							$user=explode("#",$keyword);
//							$sql="SELECT COUNT(`username`) as cnt FROM `user` WHERE `username`='".(int)$user[3]."' AND `password`='".md5($user[4])."' limit 1";
//							$data=Yii::app()->db->createCommand($sql)->queryAll();
//							if($data[0]['cnt']==1){
//								$sql="UPDATE `user` SET `wx_name`='$fromUsername' WHERE `username`='".(int)$user[3]."' limit 1";
//								Yii::app()->db->createCommand($sql)->query();
//								$Content='[愉快]认证成功';
//							}else{
//								$Content='[衰]认证失败,信息有误';
//							}
//					}elseif($keyword=='##10#'){//查看绑定账号
//							$sql="SELECT `username` FROM `user` WHERE `wx_name`='$fromUsername' limit 1";
//							$data=Yii::app()->db->createCommand($sql)->queryAll();
//							if(empty($data[0]['username'])){
//
//								$Content='[发呆]未认证';
//							}else{
//								$Content=$data[0]['username'];
//							}
//
//
//					}
//				}
                $Content=$keyword;
                $replyBody=$this->replyText($Content,$FuncFlag);
                echo $replyTitle.$replyBody;
            }
            if($type=='image'){
                $Content='/::)收到了图片消息:';
                $replyBody=$this->replyText($Content.$postObj->PicUrl,$FuncFlag);

                echo $replyTitle.$replyBody;
            }
            if($type=='location'){
                $Content='/::)收到了地理消息哈';
                $replyBody=$this->replyText($Content.' X:'.$postObj->Location_X.' Y:'.$postObj->Location_Y,$FuncFlag);
                echo $replyTitle.$replyBody;
            }
            if($type=='music'){
                $Content='/::)收到了音乐消息';
                $replyBody=$this->replyText($Content,$FuncFlag);

                echo $replyTitle.$replyBody;
            }
            if($type=='voice'){
                $Content='/::)收到了语音消息,但目前暂不支持该类型消息';
                $replyBody=$this->replyText($Content.$postObj->url.'--!',$FuncFlag);
                echo $replyTitle.$replyBody;
            }
            if($type=='event'){
                $Content='/::)收到了,点击事件';
                $type=trim($postObj->MsgType);
                $EventKey=$postObj->EventKey;
                if($EventKey=='RZ_help'){$Content='回复 ##01#账号#密码  进行认证，回复 ##10# 查看该微信绑定的账号';}
                //二维码登录
                if($EventKey==(int)$EventKey){

                }
                $replyBody=$this->replyText($Content,$FuncFlag);
                echo $replyTitle.$replyBody;
            }
            if($type=='link'){
                $Content='/::)收到了,链接事件';
                $type=trim($postObj->MsgType);
                $EventKey=$postObj->EventKey;
                $replyBody=$this->replyText($Content.$EventKey.'-**-!',$FuncFlag);
                echo $replyTitle.$replyBody;
            }
            if(!empty($fromUsername) and $replyBody==''){
                $Content='/::)收到了'.$type.'消息';
                $replyBody=$this->replyText($Content,$FuncFlag);
                echo $replyTitle.$replyBody;
            }

        }
    }

    public function actionFf(){
        $filename="log/weixin.log";

        $handle=fopen($filename,"a+");

        $str=fwrite($handle,"test\r\n");

        fclose($handle);
    }
    public function actionUser(){
        $code=$_GET['code']; //用户确认
        if(empty($code)){ exit; }

        //通过code去
        $url='https://api.weixin.qq.com/sns/oauth2/access_token';
        $jsonData=Yii::app()->curl->get($url,
            array(
                'appid'=>$this->appId,
                'secret'=>$this->appsecret,
                'code'=>$code,
                'grant_type'=>'authorization_code',
            )
        );
        if(empty($jsonData)){exit;}
        $data=CJSON::decode($jsonData);
        

        //通过code去
        $url='https://api.weixin.qq.com/sns/userinfo';
        $jsonData=Yii::app()->curl->get($url,
            array(
                'access_token'=>$data['access_token'],
                'openid'=>$data['openid'],
                'lang'=>'zh_CN',
            )
        );
        if(empty($jsonData)){exit;}
        echo $jsonData;exit;


        //$this->getAccessToken($this->appId,$this->appsecret);
    }

    public function actionT(){
        $url='http://www.mywink.top/weiXinGongZhongHao/User';
       // $scopt='snsapi_base';
        $scopt='snsapi_userinfo';

        echo 'https://open.weixin.qq.com/connect/oauth2/authorize?appid='.$this->appId.'&redirect_uri='.urlencode($url).'&response_type=code&scope='.$scopt.'&state=STATE#wechat_redirect';

    }

    public function actionSql(){
        $date=date('Ymd');
        for($i=0;$i<1000;$i++){
            $sqlval.="('".$date.sprintf("%04d", $i)."'),";
        }

        $sql="INSERT INTO `demo` (`body`) VALUES ".substr($sqlval,0,-1);
        Yii::app()->db->createCommand($sql)->query();
    }
    //分页
    public function actionPage()
	{
        $sql="select count(`id`) as `cnt` FROM `demo` ";
        $model=Yii::app()->db->createCommand($sql)->queryAll();
        $cnt=$model[0]['cnt'];

        $page = new Pagination($cnt);
        $page_list = $page->fpage(array(0,2,3,4,5,6,7,8));


        $sql="select * FROM `demo` $page->limit";
        $model=Yii::app()->db->createCommand($sql)->queryAll();

        $this->render('pagination',array('data'=>$model,'page_list'=>$page_list));
	}
    //ajax分页首页
    public function actionIndexAjax()
    {
        $this->render('index_ajax');
    }
    public function actionAjaxPage1()
    {

        $this->layout=' ';

        $sql="select count(`id`) as `cnt` FROM `demo` ";
        $model=Yii::app()->db->createCommand($sql)->queryAll();
        $cnt=$model[0]['cnt'];
        $per=30;
        $page = new PaginationAjax($cnt,$per,'Page1','','JsName1');
        $page_list = $page->fpage(array(0,2,3,4,5,6,7,8));
        $sql="select * FROM `demo` $page->limit";
        $model=Yii::app()->db->createCommand($sql)->queryAll();

        $this->render('page_ajax_li',array('data'=>$model,'page_list'=>$page_list));
    }
    public function actionAjaxPage2()
    {

        $this->layout=' ';

        $sql="select count(`id`) as `cnt` FROM `demo` ";
        $model=Yii::app()->db->createCommand($sql)->queryAll();
        $cnt=$model[0]['cnt'];
        $per=30;
        $page = new PaginationAjax($cnt,$per,'Page2','','JsName2');
        $page_list = $page->fpage(array(0,2,3,4,5,6,7,8));
        $sql="select * FROM `demo` $page->limit";
        $model=Yii::app()->db->createCommand($sql)->queryAll();

        $this->render('page_ajax_li',array('data'=>$model,'page_list'=>$page_list));
    }
    //在线编辑器
    public function actionEditor()
    {
        echo $_GET['myEditor'];
        $this->render('editor');
    }

    function __construct(){
        $this->appId=Yii::app()->params['wx_appID'];
        $this->appsecret=Yii::app()->params['wx_appsecret'];
    }



}